<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <!-- 用了一个行列布局 -->
        <tree-tools :obj="companyInfo" :is-root="true" @add-dept="onAdd" />

        <!-- 树形控件 -->
        <el-tree :data="treeData" :props="defaultProps" :default-expand-all="true">
          <tree-tools
            slot-scope="{ data }"
            :obj="data"
            @add-dept="onAdd"
            @edit-dept="onEdit"
          />
        </el-tree>
      </el-card>
    </div>

    <!-- 新增部门弹层 -->
    <!-- :visible="addDialgVisible" -->
    <!-- @update:visible="addDialgVisible = $event" -->

    <!-- 组件内部 -->
    <!-- 点击遮罩: this.$emit('update:visible', false) -->
    <add-depts
      ref="depts"
      v-model="addDialgVisible"
      :node="treeNode"
      @edit-success="loadDepartments"
      @add-success="loadDepartments"
    />
  </div>
</template>

<script>
import TreeTools from './components/tree-tools.vue'
import { getDepartmentsList } from '@/api/departments.js'
import { transListToTree } from '@/utils'
import AddDepts from './components/add-dept.vue'
export default {

  components: {
    TreeTools,
    AddDepts
  },
  data() {
    return {
      treeData: [],
      // 配置对象
      defaultProps: {
        label: 'name' // 渲染数据使用哪个字段
      },
      companyInfo: { name: '传智播客', manager: '负责人', id: '' },
      addDialgVisible: false,
      treeNode: {}
    }
  },

  created() {
    this.loadDepartments()
  },

  methods: {
    // 加载并保存组织架构数据
    async loadDepartments() {
      const res = await getDepartmentsList()
      // console.log(res)
      this.treeData = transListToTree(res.depts, '')
    },
    // 点击添加子部门
    onAdd(data) {
      this.addDialgVisible = true
      this.treeNode = data
    },
    onEdit(data) {
      // 显示弹层
      this.addDialgVisible = true
      // 传给子组件只为了做校验
      this.treeNode = data
      // 获取最新的数据进行渲染到表单的
      this.$refs.depts.getDeptsInfo(data.id)
    }
  }
}
</script>

<style scoped lang='scss'>

</style>
